import React, { useState, useEffect, useContext } from 'react';
import Websocket from '../../component/Websocket/websocket';
import { connect } from 'react-redux';
import { Input, Button, Card, Typography } from 'antd';
import * as action from './store/action';
import * as echarts from 'echarts';
import { islogin } from '../../services/action';

var myChart;
// 判断标识
var judge = 0;

const obj = {
    method: 'loginRequest',
    api: '/web/rest/user/isLogin',
    cmd: 'isLogin',
    request: {},
};

const Index = props => {
    // X轴Y轴数据
    const [abscissa_ordinate, setAbscissa_ordinate] = useState([]);

    const data = [];

    const symbolSize = 2.2;

    const option = {
        title: {
            text: '实时数据',
            left: 'center',
        },
        tooltip: {
            // triggerOn: 'click',
            formatter: function (params) {
                return 'X: ' + params.data[0].toFixed(4) + '<br>Y: ' + params.data[1].toFixed(4);
            },
            axisPointer: {
                type: 'cross',
                link: { xAxisIndex: 'all' },
                label: {
                    backgroundColor: '#6a7985',
                },
            },
        },
        grid: {
            top: '8%',
            bottom: '20%',
        },
        xAxis: {
            type: 'value',
            axisLabel: {
                interval: 'auto',
                rotate: 90,
            },
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                interval: 'auto',
                // rotate: 90,
            },
        },
        dataZoom: [
            {
                type: 'slider',
                xAxisIndex: 0,
                filterMode: 'none',
            },
            {
                type: 'slider',
                yAxisIndex: 0,
                filterMode: 'none',
            },
            {
                type: 'inside',
                xAxisIndex: 0,
                filterMode: 'none',
            },
            {
                type: 'inside',
                yAxisIndex: 0,
                filterMode: 'none',
            },
        ],
        series: [
            {
                id: 'a',
                type: 'line',
                smooth: true,
                symbolSize: symbolSize,
                data: data,
            },
        ],
    };
    // 页面加载时，挂载Echarts
    useEffect(() => {
        props.get_islogin(obj);
        myChart = echarts.init(document.getElementById('echartsData'));
        myChart.setOption(option);
        window.onresize = function () {
            myChart.resize();
        };
    }, []);
    // 接收数据时，通过监测props.websocketData来跟新数据，将数据拼接到之前的数组后面
    useEffect(() => {
        props.get_islogin(obj);
        if (judge % 80 == 0) {
            setAbscissa_ordinate([]);
        }
        // var websocketData = ;
        const { data, type } = props.websocketData;
        if (type === 'echartsData' && data != null && data != undefined) {
            var echartsData = JSON.parse(data);
            // if(data.number == 0){
            //     setAbscissa_ordinate([]);
            // }
            // 获取X轴数据
            const [...abscissaList] = echartsData.abscissaList;
            // 获取Y轴数据
            const [...ordinateList] = echartsData.ordinateList;
            var newData = [];
            for (let index = 0; index < abscissaList.length; index++) {
                let temporaryData = [];
                temporaryData.push(abscissaList[index]);
                temporaryData.push(ordinateList[index]);
                // setAbscissa_ordinate(abscissa_ordinate.concat(temporaryData));
                newData.push(temporaryData);
            }
            // 将数据拼接到state中
            setAbscissa_ordinate(abscissa_ordinate.concat(newData));
            // 判断标识+1
            judge = judge + 1;
            setTimeout(function () {
                // Add shadow circles (which is not visible) to enable drag.
                if (abscissa_ordinate.length != 0) {
                    myChart.setOption({
                        graphic: abscissa_ordinate.map(function (item, dataIndex) {
                            return {
                                type: 'circle',
                                position: myChart.convertToPixel('grid', item),
                                shape: {
                                    cx: 0,
                                    cy: 0,
                                    r: symbolSize / 2,
                                },
                                invisible: true,
                                draggable: true,
                                ondrag: function (dx, dy) {
                                    onPointDragging(dataIndex, [this.x, this.y]);
                                },
                                onmousemove: function () {
                                    showTooltip(dataIndex);
                                },
                                onmouseout: function () {
                                    hideTooltip(dataIndex);
                                },
                                z: 100,
                            };
                        }),
                    });
                }
            }, 0);
            window.addEventListener('resize', updatePosition);
            myChart.on('dataZoom', updatePosition);
            function updatePosition() {
                if (abscissa_ordinate.length != 0) {
                    myChart.setOption({
                        graphic: abscissa_ordinate.map(function (item, dataIndex) {
                            return {
                                position: myChart.convertToPixel('grid', item),
                            };
                        }),
                    });
                }
            }
            function showTooltip(dataIndex) {
                myChart.dispatchAction({
                    type: 'showTip',
                    seriesIndex: 0,
                    dataIndex: dataIndex,
                });
            }
            function hideTooltip(dataIndex) {
                myChart.dispatchAction({
                    type: 'hideTip',
                });
            }
            function onPointDragging(dataIndex, pos) {
                abscissa_ordinate[dataIndex] = myChart.convertFromPixel('grid', pos);
                // Update data
                myChart.setOption({
                    series: [
                        {
                            id: 'a',
                            data: abscissa_ordinate,
                        },
                    ],
                });
            }
        }
        var newOption = {
            series: [
                {
                    id: 'a',
                    type: 'line',
                    smooth: true,
                    symbolSize: symbolSize,
                    data: abscissa_ordinate,
                },
            ],
        };

        return myChart.setOption(newOption);
    }, [props.websocketData]);

    const extra = (
        <>
            <Button onClick={() => props.testWebsocket()} type="primary">
                获取测试数据
            </Button>
            <Button
                onClick={() => {
                    setAbscissa_ordinate([]);
                    myChart = echarts.init(document.getElementById('echartsData'));
                    myChart.setOption(option);
                    window.onresize = function () {
                        myChart.resize();
                    };
                }}
                type="primary"
                style={{ left: '10px' }}
            >
                清空
            </Button>
        </>
    );
    return (
        <>
            <Websocket />
            <Card title="Message" type="inner" extra={extra}>
                {/**封装了一个Echarts组件,只需传格式正确的数据便能描绘出可视化图像。
                 * 当然，这只是一个实例，往往开发中需根据不同的业务封装成不同的可视化图表。
                 * 封装成组件的好处在于，简化代码，降低耦合，便于维护。 */}
                <div id="echartsData" style={{ width: '80vw', height: '70vh' }}></div>
            </Card>
        </>
    );
};

const mapStateToPorps = state => ({
    // excel模版路径
    websocketData: state.websockets.websocketData,
});

const mapDispatchToProps = dispatch => ({
    testWebsocket() {
        dispatch(action.testWebsocket());
    },
    get_islogin(obj) {
        dispatch(islogin(obj));
    },
});

export default connect(mapStateToPorps, mapDispatchToProps)(Index);
